package com.zx.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.reggie.common.CustomException;
import com.zx.reggie.mapper.SetmealMapper;
import com.zx.reggie.pojo.DishFlavor;
import com.zx.reggie.pojo.Setmeal;
import com.zx.reggie.pojo.SetmealDish;
import com.zx.reggie.pojo.SetmealDto;
import com.zx.reggie.service.SetmealDishService;
import com.zx.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 张旭
 * @version 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {

        //判断id在ids中的，以及状态为在售的数据条数count
        LambdaQueryWrapper<Setmeal> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(Setmeal::getId, ids);
        lqw1.eq(Setmeal::getStatus, 1);

        int count = this.count(lqw1);
        if (count > 0) {
            throw new CustomException("套餐正在销售，无法删除");
        }
        //count不大于0,可以删除
        this.removeByIds(ids);

        //删除跟该套餐相关的菜品表中的数据
        LambdaQueryWrapper<SetmealDish> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lqw2);
    }

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {

        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);

    }


    @Override
    @Transactional
    public SetmealDto goBack(Long id) {
        //查找该id对应的套餐
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();

        BeanUtils.copyProperties(setmeal,setmealDto);

        //在套餐菜品表中查找该套餐id下关联的菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }
}
